package org.jeecg.modules.solitaire_app.app.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.solitaire_app.app.entity.YsySealCarOrder;
import org.jeecg.modules.solitaire_app.app.entity.YsySealCarOrderHis;
import org.jeecg.modules.solitaire_app.app.entity.YsyWalletLog;
import org.jeecg.modules.solitaire_app.app.mapper.YsySealCarOrderMapper;
import org.jeecg.modules.solitaire_app.app.mapper.YsyWalletLogMapper;
import org.jeecg.modules.solitaire_app.app.service.IYsySealCarOrderHisService;

import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @Description: 封车订单变化记录表
 * @Author: jeecg-boot
 * @Date: 2023-08-29
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "封车订单变化记录表")
@RestController
@RequestMapping("/app/ysySealCarOrderHis")
public class YsySealCarOrderHisController extends JeecgController<YsySealCarOrderHis, IYsySealCarOrderHisService> {
    @Autowired
    private IYsySealCarOrderHisService ysySealCarOrderHisService;
    @Autowired
    private YsySealCarOrderMapper ysySealCarOrderMapper;
    @Autowired
    private YsyWalletLogMapper ysyWalletLogMapper;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 分页列表查询
     *
     * @param ysySealCarOrderHis
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "封车订单变化记录表-分页列表查询")
    @ApiOperation(value = "封车订单变化记录表-分页列表查询", notes = "封车订单变化记录表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(YsySealCarOrderHis ysySealCarOrderHis,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<YsySealCarOrderHis> queryWrapper = QueryGenerator.initQueryWrapper(ysySealCarOrderHis, req.getParameterMap());
        Page<YsySealCarOrderHis> page = new Page<YsySealCarOrderHis>(pageNo, pageSize);
        IPage<YsySealCarOrderHis> pageList = ysySealCarOrderHisService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param ysySealCarOrderHis
     * @return
     */
    @AutoLog(value = "封车订单变化记录表-添加")
    @ApiOperation(value = "封车订单变化记录表-添加", notes = "封车订单变化记录表-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody YsySealCarOrderHis ysySealCarOrderHis) {
        YsySealCarOrder ysySealCarOrder = ysySealCarOrderMapper.selectOne(Wrappers.<YsySealCarOrder>lambdaQuery()
                .eq(YsySealCarOrder::getId, ysySealCarOrderHis.getSealCarOrder()));

        if (ysySealCarOrder.getStatus() == 3 && ysySealCarOrder.getTransferStatus() == 0) {
            return Result.error("待转单人接单，暂不能操作该订单！！！");
        }

        YsySealCarOrderHis ysySealCarOrderHisFlag = ysySealCarOrderHisService.getOne(Wrappers.<YsySealCarOrderHis>lambdaQuery()
                .eq(YsySealCarOrderHis::getSealCarOrder, ysySealCarOrderHis.getSealCarOrder())
                .eq(YsySealCarOrderHis::getType, ysySealCarOrderHis.getType()));

        if (ObjectUtil.isNotNull(ysySealCarOrderHisFlag)) {

            if (ObjectUtil.isNotNull(ysySealCarOrderHis.getPictures())) {
                ysySealCarOrderHisFlag.setPictures(ysySealCarOrderHis.getPictures());
                ysySealCarOrderHisService.updateById(ysySealCarOrderHisFlag);
                return Result.ok("修改成功！");
            } else {
                ysySealCarOrderHisService.remove(Wrappers.<YsySealCarOrderHis>lambdaQuery()
                        .eq(YsySealCarOrderHis::getSealCarOrder, ysySealCarOrderHisFlag.getSealCarOrder())
                        .eq(YsySealCarOrderHis::getType,ysySealCarOrderHisFlag.getType()));
                return Result.ok("删除成功！");
            }
        }

        ysySealCarOrderHis.setContentDesc(ysySealCarOrderHis.getType() == 0 ? "订单匹配中"
                : ysySealCarOrderHis.getType() == 1 ? ysySealCarOrder.getIncomingUserName() + "已接单"
                : ysySealCarOrderHis.getType() == 2 ? ysySealCarOrder.getIncomingUserName() + "赶往炼厂"
                : ysySealCarOrderHis.getType() == 3 ? ysySealCarOrder.getIncomingUserName() + "已到达炼厂"
                : ysySealCarOrderHis.getType() == 4 ? "验罐已提交"
                : ysySealCarOrderHis.getType() == 5 ? "进出场照片已提交"
                : ysySealCarOrderHis.getType() == 6 ? "磅单照片已提交"
                : ysySealCarOrderHis.getType() == 7 ? "物料照片已提交"
                : ysySealCarOrderHis.getType() == 8 ? "铅封照片已提交"
                : ysySealCarOrderHis.getType() == 9 ? "油样瓶照片已提交"
                : ysySealCarOrderHis.getType() == 10 ? "油样瓶照片已提交"
                : ysySealCarOrderHis.getType() == 11 ? "订单已转单"
                : ysySealCarOrderHis.getType() == 12 ? "用户已确认"
                : ysySealCarOrderHis.getType() == 13 ? "其他" : "");
        ysySealCarOrderHisService.save(ysySealCarOrderHis);
        ysySealCarOrder.setStatus(ysySealCarOrderHis.getType());
        ysySealCarOrderMapper.updateById(ysySealCarOrder);

//        if (ysySealCarOrderHis.getType() == 10) {
//
//            String userId = null;
//
//            if (ysySealCarOrder.getOrderType() == 3 && ysySealCarOrder.getTransferStatus() == 2) {
//                //要是转单,并且被转单人同意转单了，接单人是被转单人
//                userId = ysySealCarOrder.getTransferUserId();
//            } else if (ysySealCarOrder.getOrderType() == 3 && ysySealCarOrder.getTransferStatus() == 1) {
//                //如果转单订单，被转单人没有接受转单，拒绝了，接单人就是接单人
//                userId = ysySealCarOrder.getIncomingUserId();
//            } else {
//                //要是其他的，接单人就是接单人
//                userId = ysySealCarOrder.getIncomingUserId();
//            }
//
//            //安全交付袋提交，生成资金记录
//            YsyWalletLog ysyWalletLog = new YsyWalletLog();
//            ysyWalletLog.setType(ysySealCarOrder.getOrderType());
//            ysyWalletLog.setStatus(0);
//            ysyWalletLog.setCreateTime(new Date());
//            ysyWalletLog.setUserId(userId);
//            ysyWalletLog.setSealCarOrderId(ysySealCarOrder.getId());
//            ysyWalletLog.setName(ysySealCarOrder.getOrderType() == 1 ? "派单任务"
//                    : ysySealCarOrder.getOrderType() == 2 ? "抢单任务"
//                    : "转单任务");
//            ysyWalletLog.setDescript("【" + ysySealCarOrder.getRefineryCity() + "】"
//                    + ysySealCarOrder.getRefineryName() + "的"
//                    + ysyWalletLog.getName());
//            ysyWalletLog.setMoney(ysySealCarOrder.getCommission().add(ysySealCarOrder.getAdditionalPrice()));
//            ysyWalletLogMapper.insert(ysyWalletLog);
//        }

        //添加用户新状态，做通知
        redisUtil.set("userNotice:" + ysySealCarOrder.getUserId(), true);

        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param userId
     * @return
     */
    @AutoLog(value = "封车订单变化记录表-获取用户新进展")
    @ApiOperation(value = "封车订单变化记录表-获取用户新进展", notes = "封车订单变化记录表-获取用户新进展")
    @GetMapping(value = "/getUserNewNotice/{userId}")
    public Result<?> getUserNewNotice(@PathVariable("userId") String userId) {
        if (redisUtil.hasKey("userNotice:" + userId)) {
            redisUtil.del("userNotice:" + userId);
            return Result.ok("有新进展");
        }
        return Result.ok("暂无进展");
    }

    /**
     * 用户确认订单
     *
     * @param orderId
     * @return
     */
    @AutoLog(value = "封车订单变化记录表-用户确认订单")
    @ApiOperation(value = "封车订单变化记录表-用户确认订单", notes = "封车订单变化记录表-用户确认订单")
    @GetMapping(value = "/confirmOrder/{orderId}")
    public Result<?> confirmOrder(@PathVariable("orderId") String orderId) {
        YsySealCarOrder ysySealCarOrder = ysySealCarOrderMapper.selectOne(Wrappers.<YsySealCarOrder>lambdaQuery()
                .eq(YsySealCarOrder::getId, orderId));

        if (ObjectUtil.isNull(ysySealCarOrder)) {
            return Result.error("未找到该订单！！！");
        }

        if (ysySealCarOrder.getStatus() == 3 && ysySealCarOrder.getTransferStatus() == 0) {
            return Result.error("待转单人接单，暂不能操作该订单！！！");
        }

        String userId = null;

        if (ysySealCarOrder.getOrderType() == 3 && ysySealCarOrder.getTransferStatus() == 2) {
            //要是转单,并且被转单人同意转单了，接单人是被转单人
            userId = ysySealCarOrder.getTransferUserId();
        } else if (ysySealCarOrder.getOrderType() == 3 && ysySealCarOrder.getTransferStatus() == 1) {
            //如果转单订单，被转单人没有接受转单，拒绝了，接单人就是接单人
            userId = ysySealCarOrder.getIncomingUserId();
        } else {
            //要是其他的，接单人就是接单人
            userId = ysySealCarOrder.getIncomingUserId();
        }

        YsyWalletLog ysyWalletLogFlag = ysyWalletLogMapper.selectOne(Wrappers.<YsyWalletLog>lambdaQuery()
                .eq(YsyWalletLog::getUserId, userId)
                .eq(YsyWalletLog::getSealCarOrderId, orderId));

        if (ObjectUtil.isNotEmpty(ysyWalletLogFlag)) {
            return Result.error("该订单已确认，无需重复确认");
        }

        //安全交付袋提交，生成资金记录
        YsyWalletLog ysyWalletLog = new YsyWalletLog();
        ysyWalletLog.setType(ysySealCarOrder.getOrderType());
        ysyWalletLog.setStatus(0);
        ysyWalletLog.setCreateTime(new Date());
        ysyWalletLog.setUserId(userId);
        ysyWalletLog.setSealCarOrderId(ysySealCarOrder.getId());
        ysyWalletLog.setName(ysySealCarOrder.getOrderType() == 1 ? "派单任务"
                : ysySealCarOrder.getOrderType() == 2 ? "抢单任务"
                : "转单任务");
        ysyWalletLog.setDescript("【" + ysySealCarOrder.getRefineryCity() + "】"
                + ysySealCarOrder.getRefineryName() + "的"
                + ysyWalletLog.getName());
        ysyWalletLog.setMoney(ysySealCarOrder.getCommission().add(ysySealCarOrder.getAdditionalPrice()));
        ysyWalletLogMapper.insert(ysyWalletLog);

        YsySealCarOrderHis ysySealCarOrderHis = new YsySealCarOrderHis();
        ysySealCarOrderHis.setType(12);
        ysySealCarOrderHis.setContentDesc("用户已确认");
        ysySealCarOrderHis.setCreateTime(new Date());
        ysySealCarOrderHis.setSealCarOrder(orderId);
        ysySealCarOrderHisService.save(ysySealCarOrderHis);


        ysySealCarOrder.setStatus(12);//用户确认
        ysySealCarOrderMapper.updateById(ysySealCarOrder);

        return Result.ok("确认成功！");
    }


    /**
     * 编辑
     *
     * @param ysySealCarOrderHis
     * @return
     */
    @AutoLog(value = "封车订单变化记录表-编辑")
    @ApiOperation(value = "封车订单变化记录表-编辑", notes = "封车订单变化记录表-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody YsySealCarOrderHis ysySealCarOrderHis) {
        ysySealCarOrderHisService.updateById(ysySealCarOrderHis);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "封车订单变化记录表-通过id删除")
    @ApiOperation(value = "封车订单变化记录表-通过id删除", notes = "封车订单变化记录表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        ysySealCarOrderHisService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "封车订单变化记录表-批量删除")
    @ApiOperation(value = "封车订单变化记录表-批量删除", notes = "封车订单变化记录表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.ysySealCarOrderHisService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "封车订单变化记录表-通过id查询")
    @ApiOperation(value = "封车订单变化记录表-通过id查询", notes = "封车订单变化记录表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        YsySealCarOrderHis ysySealCarOrderHis = ysySealCarOrderHisService.getById(id);
        return Result.ok(ysySealCarOrderHis);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param ysySealCarOrderHis
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, YsySealCarOrderHis ysySealCarOrderHis) {
        return super.exportXls(request, ysySealCarOrderHis, YsySealCarOrderHis.class, "封车订单变化记录表");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, YsySealCarOrderHis.class);
    }

}
